package com.example.graduate.Controller;


import com.example.graduate.Bean.*;
import com.example.graduate.Service.CardsCollectService;
import com.example.graduate.Service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class MineController {

    @Autowired
    private ClientService clientService;

    @Autowired
    private CardsCollectService cardsCollectService;


    @PostMapping("/updatePlanNumber/{planNumber}")
    @ResponseBody
    public  void updatePlanNumber(@PathVariable(name = "planNumber")  String planNumber){

        Client client=new Client();
        client.setPlannumber(Integer.valueOf(planNumber));
        client.setId(1);

        clientService.updateByPrimaryKeySelective(client);

    }


    @GetMapping("/checkContinueDay/{id}")
    @ResponseBody
    public  int getCheckContinueDay(@PathVariable(name = "id")  String id){

        Date lastSignDate=clientService.selectLastDate(id);
        Date nowDate =new Date();
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        /*天数差*/
        long from1 = lastSignDate.getTime();
        long to1 = nowDate.getTime();
        int days = (int) ((to1 - from1) / (1000 * 60 * 60 * 24));
        System.out.println("两个时间之间的天数差为：" + days);
        if(days==0||days==1){
            return clientService.checkSignDay("1",lastSignDate,lastSignDate);
        }
        return 0;
    }

    @GetMapping("/checkUserId/{opendId}")
    @ResponseBody
    public  int getcheckUserId(@PathVariable(name = "opendId")  String openId){


        Client client=clientService.selectByOpenId(openId);
        if(client==null){

           Client record =new Client();
           record.setOpenid(openId);
           record.setPlannumber(20);
           clientService.insertSelective(record);
           return record.getId();
        }
        Integer currentId=client.getId();


        return  currentId;
    }






    @GetMapping("/getNowDayNumber/{id}")
    @ResponseBody
    public  Client getNowDayNumber(@PathVariable(name = "id")  String id){
        Client client=clientService.selectByPrimaryKey(Integer.valueOf(id));
        return client;
    }



    @GetMapping("/getCollective/{id}")
    @ResponseBody
    public  CardsCollect getCollective(@PathVariable(name = "id")  String id){

        return clientService.getCollectiveById(id);
    }

    @GetMapping("/getRecord/{id}")
    @ResponseBody
    public  List<Object> getRecords(@PathVariable(name="id") String id){

        List<Studyrecord> list=clientService.selectStudeyRecordByPrimaryKey(Integer.valueOf(id));
        List<Integer> number =new ArrayList<>();
        List<String>  time =new ArrayList<>();
        for(int i=0;i<list.size();i++){
            number.add(list.get(i).getNumber());
            Date date =list.get(i).getTime();
            String strDateFormat = "yyyy-MM月dd日 HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
            String item =sdf.format(list.get(i).getTime());
            time.add(item.substring(5,11));
        }
        List<Object> result=new ArrayList<>();
        result.add(number);
        result.add(time);


        return  result;
    }


    @PostMapping("/AddCollective/{userid}/{cardId}")
    @ResponseBody
    public  void AddCollective(@PathVariable(name = "userid")  String userid,@PathVariable(name="cardId") String cardId){

        UserCollective userCollective = new UserCollective();
        userCollective.setUserid(Integer.valueOf(userid));
        userCollective.setCardid(Integer.valueOf(cardId));
        clientService.addCollective(userCollective);
    }


    @PostMapping("/addHistory")
    @ResponseBody
    public  void addHistory (@RequestBody History history){
        clientService.insertHistory(history);
    }

    @GetMapping("/Commucity")
    @ResponseBody
    public  List<CommunityCatetory> getCommucity(){

        List<CommunityCatetory> communityCatetories =clientService.select();
        for(int i=0;i<communityCatetories.size();i++){
            CommunityCatetory item=communityCatetories.get(i);
            List<Post> list=clientService.selectPostByPrimaryKey(item.getId());

            item.setContengList(list);

        }
        return  communityCatetories;

    }

    @GetMapping("/SelectPostById/{id}")
    @ResponseBody
    public  Post SelectPostById(@PathVariable(name="id") String id){

        Post post=clientService.selectPostById(Integer.valueOf(id));
        Client client=clientService.selectByPrimaryKey(post.getCreatBy());
        return  clientService.selectPostById(Integer.valueOf(id));

    }

    @ResponseBody
    @RequestMapping("/uploadimg")
    public String upload(MultipartFile photo, HttpServletRequest request) throws IllegalStateException, IOException {
          OssUtil o =new OssUtil();

//        Map<String, String> map = new HashMap<String, String>();
//        String result=null;
//        try {
//            String path=null;// 文件路径
//            String type=null;// 文件类型
//            String fileName=photo.getOriginalFilename();// 文件原名称
//            System.out.println("源文件名："+fileName);
//            type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
//
//            String realPath="D:\\image";
//            System.out.println("路径名："+realPath);
//            // 自定义的文件名称
//            String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
//            // 设置存放图片文件的路径
//            path=realPath+"\\"+trueFileName;
//            System.out.println("存放图片文件的路径:"+path);
//            // 转存文件到指定的路径
//            photo.transferTo(new File(path));
//            System.out.println("文件成功上传到指定目录下");
//
//            //存储文件夹
//            String holder = "/images/";
//
//            //返回客户端的JSON
//            map.put("success", "true");
//            map.put("msg", "成功");
//            //返回服务器地址
//            map.put("file_path",trueFileName);
//            System.out.println(trueFileName);
//            result="../../../image/"+trueFileName;
//
//        } catch (IOException e) {
//            map.put("success", "false");
//        }
//        return result;
        return  o.checkImage(photo);
    }



    @GetMapping("/introduceCards/{id}")
    @ResponseBody
    public List<CardsCollect> introduceCards(@PathVariable(name = "id") String id) {






        //从数据库中获取用户的浏览行为记录，并且映射成用户稀疏矩阵和用户卡片倒排表
        List<CardsCollect> cardsCollects=new ArrayList<CardsCollect>();
        List<Client> allUser = clientService.selectAll();
        Integer N = allUser.size();
        int[][] sparseMatrix = new int[N][N];//建立用户稀疏矩阵，用于用户相似度计算【相似度矩阵】
        Map<String, Integer> userItemLength = new TreeMap<>();//存储每一个用户对应的不同物品总数  eg: A 3
        Map<String, Set<String>> itemUserCollection = new HashMap<>();//建立物品到用户的倒排表 eg: a A B
        Set<String> items = new HashSet<>();//辅助存储物品集合
        Map<String, Integer> userID = new HashMap<>();//辅助存储每一个用户的用户ID映射
        Map<Integer, String> idUser = new HashMap<>();//辅助存储每一个ID对应的用户映射
        for (int i = 0; i < N; i++) {//依次处理N个用户 输入数据  以空格间隔
            Integer currenUserId = allUser.get(i).getId();
            List<History> historyList = clientService.selectHistoryById(currenUserId);
            userItemLength.put(String.valueOf(currenUserId), historyList.size());//eg: A 3
            userID.put(String.valueOf(currenUserId), i);//用户ID与稀疏矩阵建立对应关系
            idUser.put(i, String.valueOf(currenUserId));
            //建立物品--用户倒排表
            for (int j = 0; j < historyList.size(); j++) {
                if (items.contains(String.valueOf(historyList.get(j).getCardsid()))) {//如果已经包含对应的物品--用户映射，直接添加对应的用户
                    itemUserCollection.get(String.valueOf(historyList.get(j).getCardsid())).add(String.valueOf(currenUserId));
                } else {//否则创建对应物品--用户集合映射
                    items.add(String.valueOf(historyList.get(j).getCardsid()));
                    itemUserCollection.put(String.valueOf(historyList.get(j).getCardsid()), new HashSet<String>());//创建物品--用户倒排关系
                    itemUserCollection.get(String.valueOf(historyList.get(j).getCardsid())).add(String.valueOf(currenUserId));
                }
            }
        }
        Set<Map.Entry<String, Set<String>>> entrySet = itemUserCollection.entrySet();
        Iterator<Map.Entry<String, Set<String>>> iterator = entrySet.iterator();
        while(iterator.hasNext()){
            Set<String> commonUsers = iterator.next().getValue();
            System.out.println(commonUsers);
            for (String user_u : commonUsers) {
                for (String user_v : commonUsers) {
                    if(user_u.equals(user_v)){
                        continue;
                    }
                    sparseMatrix[userID.get(user_u)][userID.get(user_v)] += 1;//计算用户u与用户v都有正反馈的物品总数
                }
            }
        }
        System.out.println(userItemLength.toString());
        System.out.println(userID.get(id));
        //计算用户之间的相似度【余弦相似性】
        int recommendUserId = userID.get(id);
        System.out.println(recommendUserId);
        System.out.println(sparseMatrix.toString());
        System.out.println(idUser.toString());
        System.out.println(userItemLength.toString());
        for (int j = 0;j < sparseMatrix.length; j++) {
            if(j != recommendUserId){
                System.out.println(idUser.get(recommendUserId)+"--"+idUser.get(j)+"相似度:"
                        + sparseMatrix[recommendUserId][j]/Math.sqrt(userItemLength.get(idUser.get(recommendUserId))*userItemLength.get(idUser.get(j))));
            }
        }
        //计算指定用户recommendUser的物品推荐度
        for(String item: items){//遍历每一件物品
            Set<String> users = itemUserCollection.get(item);//得到购买当前物品的所有用户集合
            if(!users.contains(id)){//如果被推荐用户没有购买当前物品，则进行推荐度计算
                double itemRecommendDegree = 0.0;//发现一个商品目标用户还没浏览过的，先把推荐值默认为0
                for(String user: users){
                    //推荐度计算，这是累加，这个商品你的相似用户看的越多，推荐值越高，简单来说就是某个商品的推荐值是其商品用户用户中，目标用户的相似用户的相似度的累加
                    itemRecommendDegree += sparseMatrix[userID.get(id)][userID.get(user)]/Math.sqrt(userItemLength.get(id)*userItemLength.get(user));
                }
                CardsCollect cardsCollect=cardsCollectService.selectCards(Integer.valueOf(item));
                cardsCollects.add(cardsCollect);
                System.out.println("The item "+item+" for "+id +"'s recommended degree:"+itemRecommendDegree);
            }
        }
        return cardsCollects;
    }





}
